import java.util.Stack;

public class Test1 {
    //leetcode 验证栈序列
    //https://leetcode.cn/problems/validate-stack-sequences/description/
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int index1 = 0, index2 = 0;
        int len = pushed.length;
        Stack<Integer> stack = new Stack<>();
        while (index1 < len && index2 < len) {
            while (index1 < len && pushed[index1] != popped[index2]) {
                stack.add(pushed[index1++]);
            }
            if (index1 < len) {
                stack.add(pushed[index1]);
            }
            while (!stack.isEmpty() && index2 < len && stack.peek() == popped[index2]) {
                stack.pop();
                index2++;
            }
            index1++;
        }
        return index1 == len && index2 == len && stack.isEmpty();
    }

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        int[] pushed = {1,2,3,4,5};
        int[] popped = {4,5,3,2,1};
        test1.validateStackSequences(pushed,popped);
        System.out.println(777);
    }
}
